package com.zhentao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.pojo.*;
import com.zhentao.service.TcClassService;
import com.zhentao.mapper.TcClassMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.stream.Collectors;

/**
* @author 86137
* @description 针对表【tc_class(班级信息表)】的数据库操作Service实现
* @createDate 2025-09-26 14:31:58
*/
@Service
public class TcClassServiceImpl extends ServiceImpl<TcClassMapper, TcClass>
    implements TcClassService{

    @Autowired
    private TcClassMapper tcClassMapper;

    @Override
    public ClassUserDTO getClassWithUsers(Integer classId) {
        List<Map<String, Object>> resultList = tcClassMapper.getClassWithUsersRaw(classId);
        if (resultList.isEmpty()) {
            return null;
        }
        
        // 处理查询结果，将用户信息分组
        ClassUserDTO result = new ClassUserDTO();
        TcClass classInfo = new TcClass();
        List<TcUser> users = new ArrayList<>();
        
        // 从第一条记录获取班级信息
        Map<String, Object> firstRecord = resultList.get(0);
        if (firstRecord != null) {
            classInfo.setClassId(getIntegerValue(firstRecord.get("class_id")));
            classInfo.setClassName((String) firstRecord.get("class_name"));
            classInfo.setClassCode((String) firstRecord.get("class_code"));
            classInfo.setCreatorUserId(getIntegerValue(firstRecord.get("creator_user_id")));
            classInfo.setGrade((String) firstRecord.get("grade"));
            classInfo.setSubject((String) firstRecord.get("subject"));
            classInfo.setIsHeadteacher(getIntegerValue(firstRecord.get("is_headteacher")));
            classInfo.setCreateTime((java.util.Date) firstRecord.get("create_time"));
        }
        
        // 收集所有用户信息
        for (Map<String, Object> record : resultList) {
            if (record.get("user_id") != null) {
                TcUser user = new TcUser();
                user.setUserId(getIntegerValue(record.get("user_id")));
                user.setOpenid((String) record.get("openid"));
                user.setNickname((String) record.get("nickname"));
                user.setAvatarUrl((String) record.get("avatar_url"));
                user.setPhone((String) record.get("phone"));
                user.setIdentity((String) record.get("identity"));
                user.setAvatar((String) record.get("avatar"));
                user.setTokenExpires((java.util.Date) record.get("token_expires"));
                user.setCreateTime((java.util.Date) record.get("user_create_time"));
                user.setUpdateTime((java.util.Date) record.get("update_time"));
                // 由于tc_user表没有status字段，我们设置默认值
                // user.setStatus(1); // 默认状态为正常
                users.add(user);
            }
        }
        
        // 统计用户数量
        long teacherCount = users.stream().filter(u -> "老师".equals(u.getIdentity())).count();
        long studentCount = users.stream().filter(u -> "学生".equals(u.getIdentity())).count();
        long parentCount = users.stream().filter(u -> "家长".equals(u.getIdentity())).count();
        
        result.setClassInfo(classInfo);
        result.setUsers(users);
        result.setUserCount(users.size());
        result.setTeacherCount((int) teacherCount);
        result.setStudentCount((int) studentCount);
        result.setParentCount((int) parentCount);
        
        return result;
    }

    @Override
    public List<ClassUserDTO> getAllClassesWithUsers() {
        List<Map<String, Object>> resultList = tcClassMapper.getAllClassesWithUsersRaw();
        return processClassUserResultsFromMap(resultList);
    }

    @Override
    public List<ClassUserDTO> getMyClassesWithUsers(Integer creatorUserId) {
        List<Map<String, Object>> resultList = tcClassMapper.getMyClassesWithUsersRaw(creatorUserId);
        return processClassUserResultsFromMap(resultList);
    }

    @Override
    public Map<String, Object> getClassUserStatistics(Integer classId) {
        return tcClassMapper.getClassUserStatistics(classId);
    }

    @Override
    public List<Map<String, Object>> getClassWithUsersRaw(Integer classId) {
        return tcClassMapper.getClassWithUsersRaw(classId);
    }

    @Override
    public TcClass getClassByClassId(Integer classId) {
        return tcClassMapper.getClassByClassId(classId);
    }

    @Override
    public List<TcClass> getClassesByClassIds(List<Integer> classIds) {
        if (classIds == null || classIds.isEmpty()) {
            return new ArrayList<>();
        }
        return tcClassMapper.getClassesByClassIds(classIds);
    }

    // ==================== 三表联查：学生-班级-教师 ====================
    
    @Override
    public StudentClassTeacherDTO getStudentClassTeacherByStudentId(Long studentId) {
        List<Map<String, Object>> resultList = tcClassMapper.getStudentClassTeacherByStudentId(studentId);
        if (resultList.isEmpty()) {
            return null;
        }
        return processStudentClassTeacherResult(resultList.get(0));
    }

    @Override
    public List<StudentClassTeacherDTO> getStudentClassTeacherByClassId(Integer classId) {
        List<Map<String, Object>> resultList = tcClassMapper.getStudentClassTeacherByClassId(classId);
        return processStudentClassTeacherResults(resultList);
    }

    @Override
    public List<StudentClassTeacherDTO> getStudentClassTeacherByTeacherId(Integer teacherId) {
        List<Map<String, Object>> resultList = tcClassMapper.getStudentClassTeacherByTeacherId(teacherId);
        return processStudentClassTeacherResults(resultList);
    }

    @Override
    public List<StudentClassTeacherDTO> getAllStudentClassTeacher() {
        List<Map<String, Object>> resultList = tcClassMapper.getAllStudentClassTeacher();
        return processStudentClassTeacherResults(resultList);
    }

    @Override
    public List<StudentClassTeacherDTO> searchStudentClassTeacher(String keyword, String grade, String subject) {
        List<Map<String, Object>> resultList = tcClassMapper.searchStudentClassTeacher(keyword, grade, subject);
        return processStudentClassTeacherResults(resultList);
    }

    /**
     * 处理班级用户查询结果（从Map数据）
     * @param resultList 原始查询结果
     * @return 处理后的结果列表
     */
    private List<ClassUserDTO> processClassUserResultsFromMap(List<Map<String, Object>> resultList) {
        if (resultList.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 按班级ID分组
        Map<Integer, List<Map<String, Object>>> groupedByClass = resultList.stream()
            .collect(Collectors.groupingBy(record -> (Integer) record.get("class_id")));
        
        List<ClassUserDTO> processedResults = new ArrayList<>();
        
        for (Map.Entry<Integer, List<Map<String, Object>>> entry : groupedByClass.entrySet()) {
            List<Map<String, Object>> classRecords = entry.getValue();
            ClassUserDTO result = new ClassUserDTO();
            
            // 获取班级信息（从第一条记录）
            if (!classRecords.isEmpty()) {
                Map<String, Object> firstRecord = classRecords.get(0);
                TcClass classInfo = new TcClass();
                classInfo.setClassId(getIntegerValue(firstRecord.get("class_id")));
                classInfo.setClassName((String) firstRecord.get("class_name"));
                classInfo.setClassCode((String) firstRecord.get("class_code"));
                classInfo.setCreatorUserId(getIntegerValue(firstRecord.get("creator_user_id")));
                classInfo.setGrade((String) firstRecord.get("grade"));
                classInfo.setSubject((String) firstRecord.get("subject"));
                classInfo.setIsHeadteacher(getIntegerValue(firstRecord.get("is_headteacher")));
                classInfo.setCreateTime((java.util.Date) firstRecord.get("create_time"));
                result.setClassInfo(classInfo);
            }
            
            // 收集该班级的所有用户
            List<TcUser> users = new ArrayList<>();
            for (Map<String, Object> record : classRecords) {
                if (record.get("user_id") != null) {
                    TcUser user = new TcUser();
                    user.setUserId(getIntegerValue(record.get("user_id")));
                    user.setOpenid((String) record.get("openid"));
                    user.setNickname((String) record.get("nickname"));
                    user.setAvatarUrl((String) record.get("avatar_url"));
                    user.setPhone((String) record.get("phone"));
                    user.setIdentity((String) record.get("identity"));
                    user.setAvatar((String) record.get("avatar"));
                    user.setTokenExpires((java.util.Date) record.get("token_expires"));
                    user.setCreateTime((java.util.Date) record.get("user_create_time"));
                    user.setUpdateTime((java.util.Date) record.get("update_time"));
                    // 由于tc_user表没有status字段，我们设置默认值
                    // user.setStatus(1); // 默认状态为正常
                    users.add(user);
                }
            }
            
            // 统计用户数量
            long teacherCount = users.stream().filter(u -> "老师".equals(u.getIdentity())).count();
            long studentCount = users.stream().filter(u -> "学生".equals(u.getIdentity())).count();
            long parentCount = users.stream().filter(u -> "家长".equals(u.getIdentity())).count();
            
            result.setUsers(users);
            result.setUserCount(users.size());
            result.setTeacherCount((int) teacherCount);
            result.setStudentCount((int) studentCount);
            result.setParentCount((int) parentCount);
            
            processedResults.add(result);
        }
        
        return processedResults;
    }

    /**
     * 安全获取Integer值
     * @param value 原始值
     * @return Integer值，如果转换失败返回null
     */
    private Integer getIntegerValue(Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof Integer) {
            return (Integer) value;
        }
        if (value instanceof Long) {
            return ((Long) value).intValue();
        }
        if (value instanceof Boolean) {
            return ((Boolean) value) ? 1 : 0;
        }
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        try {
            return Integer.valueOf(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * 安全获取Long值
     * @param value 原始值
     * @return Long值，如果转换失败返回null
     */
    private Long getLongValue(Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof Long) {
            return (Long) value;
        }
        if (value instanceof Integer) {
            return ((Integer) value).longValue();
        }
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        try {
            return Long.valueOf(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * 处理单个学生-班级-教师查询结果
     * @param record 原始查询记录
     * @return 处理后的结果
     */
    private StudentClassTeacherDTO processStudentClassTeacherResult(Map<String, Object> record) {
        if (record == null) {
            return null;
        }
        
        StudentClassTeacherDTO result = new StudentClassTeacherDTO();
        
        // 学生信息
        WxUser student = new WxUser();
        student.setId(getLongValue(record.get("student_id")));
        student.setOpenid((String) record.get("student_openid"));
        student.setNickname((String) record.get("student_name"));
        student.setPhone((String) record.get("student_phone"));
        student.setIdentity((String) record.get("student_identity"));
        student.setAvatarUrl((String) record.get("student_avatar"));
        student.setCreateTime(convertToDate(record.get("student_create_time")));
        result.setStudent(student);
        
        // 班级信息
        TcClass classInfo = new TcClass();
        classInfo.setClassId(getIntegerValue(record.get("class_id")));
        classInfo.setClassName((String) record.get("class_name"));
        classInfo.setClassCode((String) record.get("class_code"));
        classInfo.setCreatorUserId(getIntegerValue(record.get("creator_user_id")));
        classInfo.setGrade((String) record.get("grade"));
        classInfo.setSubject((String) record.get("subject"));
        classInfo.setIsHeadteacher(getIntegerValue(record.get("is_headteacher")));
        classInfo.setCreateTime(convertToDate(record.get("class_create_time")));
        result.setClassInfo(classInfo);
        
        // 教师信息
        TcUser teacher = new TcUser();
        teacher.setUserId(getIntegerValue(record.get("teacher_id")));
        teacher.setOpenid((String) record.get("teacher_openid"));
        teacher.setNickname((String) record.get("teacher_name"));
        teacher.setPhone((String) record.get("teacher_phone"));
        teacher.setIdentity((String) record.get("teacher_identity"));
        teacher.setAvatarUrl((String) record.get("teacher_avatar"));
        teacher.setCreateTime(convertToDate(record.get("teacher_create_time")));
        result.setTeacher(teacher);
        
        // 设置简化字段
        result.setStudentId(student.getId());
        result.setStudentName(student.getNickname());
        result.setStudentPhone(student.getPhone());
        result.setStudentIdentity(student.getIdentity());
        result.setClassId(classInfo.getClassId());
        result.setClassName(classInfo.getClassName());
        result.setClassCode(classInfo.getClassCode());
        result.setGrade(classInfo.getGrade());
        result.setSubject(classInfo.getSubject());
        result.setTeacherId(teacher.getUserId());
        result.setTeacherName(teacher.getNickname());
        result.setTeacherPhone(teacher.getPhone());
        result.setTeacherIdentity(teacher.getIdentity());
        result.setCreateTime(convertToDate(record.get("class_create_time")));
        
        return result;
    }

    /**
     * 处理多个学生-班级-教师查询结果
     * @param resultList 原始查询结果列表
     * @return 处理后的结果列表
     */
    private List<StudentClassTeacherDTO> processStudentClassTeacherResults(List<Map<String, Object>> resultList) {
        if (resultList == null || resultList.isEmpty()) {
            return new ArrayList<>();
        }
        
        List<StudentClassTeacherDTO> processedResults = new ArrayList<>();
        for (Map<String, Object> record : resultList) {
            StudentClassTeacherDTO result = processStudentClassTeacherResult(record);
            if (result != null) {
                processedResults.add(result);
            }
        }
        
        return processedResults;
    }

    /**
     * 安全转换日期类型
     * @param value 原始值
     * @return Date值，如果转换失败返回null
     */
    private java.util.Date convertToDate(Object value) {
        if (value == null) {
            return null;
        }
        
        try {
            // 如果已经是Date类型
            if (value instanceof java.util.Date) {
                return (java.util.Date) value;
            }
            
            // 如果是LocalDateTime类型
            if (value instanceof java.time.LocalDateTime) {
                java.time.LocalDateTime localDateTime = (java.time.LocalDateTime) value;
                return java.util.Date.from(localDateTime.atZone(java.time.ZoneId.systemDefault()).toInstant());
            }
            
            // 如果是LocalDate类型
            if (value instanceof java.time.LocalDate localDate) {
                return java.util.Date.from(localDate.atStartOfDay(java.time.ZoneId.systemDefault()).toInstant());
            }
            
            // 如果是Timestamp类型
            if (value instanceof java.sql.Timestamp) {
                return new java.util.Date(((java.sql.Timestamp) value).getTime());
            }
            
            // 如果是String类型，尝试解析
            if (value instanceof String) {
                String dateStr = (String) value;
                if (!dateStr.trim().isEmpty()) {
                    // 尝试解析常见的日期格式
                    try {
                        return java.sql.Timestamp.valueOf(dateStr);
                    } catch (Exception e) {
                        // 如果解析失败，返回null
                        return null;
                    }
                }
            }
            
            return null;
        } catch (Exception e) {
            // 转换失败，返回null
            return null;
        }
    }

    // ==================== 双表联查：用户-班级 ====================
    
    @Override
    public List<Map<String, Object>> getAllUserWithClass() {
        System.out.println("=== Service层：开始执行 getAllUserWithClass ===");
        List<Map<String, Object>> result = tcClassMapper.getAllUserWithClass();
        System.out.println("=== Service层：查询结果数量: " + (result != null ? result.size() : "null") + " ===");
        if (result != null && !result.isEmpty()) {
            System.out.println("=== Service层：第一条数据: " + result.get(0) + " ===");
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> getAllStudentWithClass() {
        return tcClassMapper.getAllStudentWithClass();
    }

    @Override
    public List<Map<String, Object>> getClassUsersWithClass(Integer classId) {
        return tcClassMapper.getClassUsersWithClass(classId);
    }

    @Override
    public List<Map<String, Object>> getClassStudentsWithClass(Integer classId) {
        return tcClassMapper.getClassStudentsWithClass(classId);
    }

    /**
     * 测试wx_user表数据
     * @return wx_user表数据
     */
    public List<Map<String, Object>> testWxUserTable() {
        System.out.println("=== 测试wx_user表查询 ===");
        return tcClassMapper.testWxUserTable();
    }

    /**
     * 测试LEFT JOIN查询
     * @return 联查结果
     */
    public List<Map<String, Object>> testLeftJoin() {
        System.out.println("=== 测试LEFT JOIN查询 ===");
        return tcClassMapper.testLeftJoin();
    }

}




